/* 
 * Copyright (c) 2011-, Agilord Kft. - All Rights Reserved.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.agilord.dragonflyp4;

import java.io.File;
import java.util.LinkedList;
import java.util.Queue;

/**
 * Will scan and iterate the files in the provided directories.
 * 
 * @author Istvan Soos
 * @since 1.0
 */
public class FileScanner {

	protected Queue<File> directories = new LinkedList<File>();
	protected Queue<File> files = new LinkedList<File>();

	public FileScanner(String... args) {
		super();
		scanCLIArgs(args);
	}

	public void scanCLIArgs(String[] args) {
		for (String arg : args) {
			File f = new File(arg);
			if (!f.exists())
				continue;
			if (f.isDirectory()) {
				directories.add(f);
			} else {
				if (isPhotoFile(f)) {
					files.add(f);
				}
			}
		}
	}

	public boolean isPhotoFile(File file) {
		boolean validExt = false;
		String namelc = file.getName().toLowerCase();
		for (String ext : Configuration.get().getExtensions()) {
			if (namelc.endsWith(ext)) {
				validExt = true;
				break;
			}
		}

		if (!validExt)
			return false;

		return true;
	}

	public File next() {
		for (;;) {
			if (files.isEmpty() && directories.isEmpty())
				return null;

			if (!files.isEmpty())
				return files.poll();

			File[] fs = directories.poll().listFiles();
			if (fs == null)
				continue;
			for (File f : fs) {
				if (f.isDirectory()) {
					directories.add(f);
				} else if (isPhotoFile(f)) {
					files.add(f);
				}
			}
		}
	}
}
